# Copyright 2024 Bytedance Ltd. and/or its affiliates
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from verl.single_controller.base.worker import Worker


class DPEngineWorker(Worker):

    def __init__(self, *args, **kwargs):
        # todo: extract _world_size etc. from kwargs and inject in super().__init__()
        Worker.__init__(self, *args, **kwargs)

    def init(self):
        raise NotImplementedError

    def add_engine(self, model, dp_config):
        raise NotImplementedError

    def execute_engine(self, method_name, *args, **kwargs):
        print(f"execute_engine called with method={method_name}")
        func = getattr(self._engine, method_name)
        return func(*args, **kwargs)

    def execute_module(self, method_name, *args, **kwargs):
        print(f"execute_module called with method={method_name}")
        func = getattr(self._engine.module, method_name)
        return func(*args, **kwargs)

    def get_model_size_on_rank_zero(self):
        import torch
        from verl.utils.model import get_model_size
        if torch.distributed.get_rank() == 0:
            # print("model print on rank 0: ", self._model)
            module_size, module_size_scale = get_model_size(self._model)
            return module_size, module_size_scale
        return None
